package com.sl.au.service;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
/**网易云信
 * @author Neil
 *
 */
@Service("smsService")
public class SMSService {
	 // 日志  
    private static final Logger log = Logger.getLogger(SMSService.class);  
 	
	private  final  String appKey = "1a4c2a77e55c246dca600ac94903f50c";
	private  final  String secretKey = "a0eb0561da7d";
	private final String tempId="3055539";
	private final String sendUrl="https://api.netease.im/sms/sendtemplate.action";

	private RestTemplate restTemplate;
	/*@Autowired
	AsyncRestTemplate asyncRestTemplate;*/
	@Autowired
	CheckSumBuilder csBuilder;
	
	public SMSService(){
		this.restTemplate=new RestTemplate();
	}
	
	
	/**
	 * @param content
	 * @return{
  	*"code":200,
  	*"msg":"sendid", 
  	*"obj":123
	*}
	 */
	//@Async
	public JSONObject sendSMS(String content){
		
		 HttpHeaders headers = new HttpHeaders();
		 MediaType type = MediaType.parseMediaType("application/x-www-form-urlencoded;charset=utf-8");
		 headers.setContentType(type);
		 //headers.add("Accept", MediaType.APPLICATION_JSON.toString());
		 headers.add("AppKey", appKey);
		Long l=(new Date()).getTime();
		String curTime=(l/1000L)+"";
		String nonce="8888888";
		 headers.add("CurTime", curTime);
		 String checkSum= csBuilder.getCheckSum(secretKey, nonce, curTime);
		 headers.add("CheckSum", checkSum);
		 headers.add("Nonce", nonce);
		 
		 JSONObject params= new JSONObject();
		 
		 params.put("templateId", tempId);
		 params.put("mobiles","[15223125196]");
		 params.put("params", content);
		 HttpEntity<String> formEntity = new HttpEntity<String>(params.toString(), headers);
		 
		JSONObject json=this.restTemplate.postForEntity(this.sendUrl, formEntity,JSONObject.class).getBody();
		return json;
	}
	/*public String asyncReq(){  
        String url = "http://localhost:8080/jsonAsync";  
        ListenableFuture<ResponseEntity<JSONObject>> future = asyncRestTemplate.getForEntity(url, JSONObject.class);  
        future.addCallback(new SuccessCallback<ResponseEntity<JSONObject>>() {  
            public void onSuccess(ResponseEntity<JSONObject> result) {  
               // System.out.println(result.getBody().toJSONString());  
            }  
        }, new FailureCallback() {  
            public void onFailure(Throwable ex) {  
                System.out.println("onFailure:"+ex);  
            }  
        });  
        return "this is async sample";  
    }  
    
	 */
	public void  sendSMS2(String content,String mobiles) { 
		 DefaultHttpClient httpClient = new DefaultHttpClient();	      
	        HttpPost httpPost = new HttpPost(this.sendUrl);
	  
			String nonce="8888888";
	    String curTime = String.valueOf((new Date()).getTime() / 1000L);
        String checkSum = CheckSumBuilder.getCheckSum(this.secretKey, nonce ,curTime);//参考 计算CheckSum的java代码

        // 设置请求的header
        httpPost.addHeader("AppKey", appKey);
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        // 设置请求的参数
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    
        nvps.add(new BasicNameValuePair("mobiles",mobiles));
        nvps.add(new BasicNameValuePair("templateid", tempId));      
        nvps.add(new BasicNameValuePair("params", "['"+content+"']"));
        try {
			httpPost.setEntity(new UrlEncodedFormEntity(nvps,"utf-8"));
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        try {
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
			   // 执行请求
	        HttpResponse response = httpClient.execute(httpPost);

	        // 打印执行结果
	        System.out.println(EntityUtils.toString(response.getEntity(), "utf-8"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

     
		
	}

}
